<?php
/**
 * 快速删除
 * @Copyright (C) 2018 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
header("content-Type: text/html; charset=utf-8");
//配置结束
$action=@$_GET['action'];
if($action=="del"){
    $del=new del();
    $arr=$del->execute();
    if(is_array($arr)){
        echo implode("\n<br>",$arr);
        echo "<script>location.href='del.php?action=del';</script>";
    }else{
        echo $arr; 
    }            
}else{
	echo "<a href='?action=del'>点击清除缓存</a>";
}

class del{
    private $path="./Data/Runtime/Temp/";//在些设置所删除的目录.为当前目录 如：删除path目录，引号里请添path;
    private $guolv="del.php";//设置需要过滤的文件或文件夹用英文状态下,号分隔
    private $steep = 500;//每页删除数量
    public function __construct($path='',$guolv=''){
        if(!empty($path))$this->path = $path;
        if(!empty($guolv))$this->guolv = $guolv;
        $arrbaselv=array('.','..');
        if($this->guolv && !is_array($this->guolv))$this->guolv=explode(',',$this->guolv);
        $this->guolv=$this->guolv?array_merge($this->guolv,$arrbaselv):$arrbaselv;
    }
    public function execute(){//执行
        $allfiles=$this->recurdir();
        if($allfiles){
            return $this->remove_file($allfiles);
        }else{
            return 'success';
        }
    }//删除文件
    private function remove_file($file){
        $arr=array();
        foreach($file as $fn) {
            if(is_array($fn)){
                $resarr= $this->remove_file($fn);
                if($arr && $resarr)$arr=array_merge($arr,$resarr);
                else $arr=$arr?$arr:$resarr;
            }else{
                $arr[]=$fn;
        		if (!is_writable($fn))@chmod($fn, 0777);
        		if(is_dir($fn)){@rmdir($fn);}else{@unlink($fn);}
            }
        }
        return array_unique($arr);
    }//扫描目录
    private function recurdir($pathname=''){
        if(empty($pathname))$pathname=$this->path;
    	$result=array();$temp=array();
    	if(!is_dir($pathname) || !is_readable($pathname))return null;//检查目录是否有效和可读  
    	$resourse=opendir($pathname);//得到目录下的所有文件夹
        $key=0;
        while($filename=readdir($resourse)){
    		if(in_array($filename,$this->guolv))continue;//如果是“.”或者“..”的话则略过
    		$fullname =$pathname . "/" .$filename;//得到文件完整名字
    	    if((!is_dir($fullname) && $key>$this->steep))break;
    		$temp[]=$fullname;
    		if(is_dir($fullname)){//如果该文件是目录的话，递归调用recurdir
    			$nowpath=explode("/",$fullname);
    			if(in_array($nowpath[count($nowpath)-1],$this->guolv))continue;
    			$result[$filename] = $this->recurdir($fullname);}
            $key++;
    	}
    	foreach($temp as $f){$result[]=$f;}//最后把临时数组中的内容添加到结果数组，确保目录在前，文件在后
    	return $result;
    }
}
?> 